local extension = Package("ling5")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"
local LUtil = require "packages/lingling/utility/ling_util"

local yangjian = General(extension, "lingling__yangjian", "sui", 5)
local daxing = fk.CreateViewAsSkill{
  name = "lingling__daxing",
  pattern = "duel,ex_nihilo",
  card_filter = function(self, to_select, selected)
    if #selected >= 2 then
      return false
    elseif #selected > 0 then
      return Fk:getCardById(to_select):compareColorWith(Fk:getCardById(selected[1]))
    else
      local color = Fk:getCardById(to_select).color
      local c
      if color == Card.Red then
        c = Fk:cloneCard("ex_nihilo")
      elseif color == Card.Black then
        c = Fk:cloneCard("duel")
      else
        return false
      end
      return (Fk.currentResponsePattern == nil and c.skill:canUse(Self, c))
      or (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(c))
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then
      return nil
    end
    local color = Fk:getCardById(cards[1]).color
    local c
    if color == Card.Red then
      c = Fk:cloneCard("ex_nihilo")
    elseif color == Card.Black then
      c = Fk:cloneCard("duel")
    else
      return nil
    end
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
}
local qingzha = fk.CreateTriggerSkill{
  name = "lingling__qingzha",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then 
    local room = player.room
    local move_event = room.logic:getCurrentEvent()
    local parent_event = move_event.parent
    local card_ids = {}
    self.cost_data ={{}}
    if parent_event ~= nil then
      if parent_event.event == GameEvent.UseCard then
        local parent_data = parent_event.data[1]
        if parent_data.from == player.id and parent_data.card.type == Card.TypeTrick then
          card_ids = room:getSubcardsByRule(parent_data.card)
        end
        if parent_data.damageDealt then
          local targets = TargetGroup:getRealTargets(parent_data.tos)
          for _, pid in ipairs(targets) do
            if parent_data.damageDealt[pid] and parent_data.damageDealt[pid]>0 then
              table.insertIfNeed(self.cost_data,"must")
              break
            end
          end
        end
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        --[[if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) then
               table.insert(self.cost_data[1],info.cardId)
            end
          end
        else--]]if #card_ids > 0 then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.Processing and table.contains(card_ids, info.cardId) then
              table.insert(self.cost_data[1],info.cardId)
            end
          end
        end
      end
    end
    if #table.filter(self.cost_data[1], function(id) return room:getCardArea(id) == Card.DiscardPile end) >0 then
      self.cost_data[1] = table.filter(self.cost_data[1], function(id) return room:getCardArea(id) == Card.DiscardPile end)
    return true
    end
  end
end
end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if #self.cost_data>1 then
      return true
    else
      return room:askForSkillInvoke(player,self.name)
    end
  end,
  on_use = function(self, event, target, player, data)
   local room = player.room
   room:changeMaxHp(player, -1)
   if not player.dead then
    room:moveCardTo(self.cost_data[1], Player.Hand,player, fk.ReasonPrey, self.name, nil, true, player.id)
   end
  end,
}
yangjian:addSkill(daxing)
yangjian:addSkill(qingzha)
Fk:loadTranslationTable{
  ["lingling__yangjian"] = "杨坚",
  ["#lingling__yangjian"] = "晦明藏用",
  ["designer:lingling__yangjian"] = "伶",
  ["illustrator:lingling__yangjian"] = "珊瑚虫",

  ["lingling__daxing"] = "大兴",
  [":lingling__daxing"] = "你可以将两张红色牌当【无中生有】使用，或将两张黑色牌当【决斗】使用。",
  ["lingling__qingzha"] = "倾扎",
  [":lingling__qingzha"] = "每回合限一次，你使用的锦囊牌进入弃牌堆后，你可以减1点体力上限获得之，若此牌对目标造成了伤害，你必须如此做。"..
  "<br><br> <font color='#a40000'>普六茹坚相貌非常，人颇狡诈。</font>",
}

local yangguang = General(extension, "lingling__yangguang", "sui", 5)
local piyun = fk.CreateTriggerSkill{
  name = "lingling__piyun",
  anim_type = "support",
  events = {fk.TurnStart, fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.TurnStart then
        return true
      elseif event == fk.TurnEnd then
        return table.find(player.room:getOtherPlayers(player), function (p)
          return not p:hasSkill(self, true)
        end)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.TurnStart then
      self.cost_data = nil
      return true
    elseif event == fk.TurnEnd then
      local room = player.room
      local targets = table.filter(room:getOtherPlayers(player), function (p)
        return not p:hasSkill(self, true)
      end)
      local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#lingling__piyun-choose", self.name, true)
      if #to > 0 then
        self.cost_data = {tos = to}
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      player:drawCards(1, self.name)
      if not player.dead and not player:isNude() then
        local targets = room:getOtherPlayers(player)
        if #targets == 0 then return end
        room:askForYiji(player, player:getCardIds("he"), targets, self.name, 1, 1, "#lingling__piyun-give")
      end
    elseif event == fk.TurnEnd then
      room:changeMaxHp(player, -1)
      local to = room:getPlayerById(self.cost_data.tos[1])
      if not to.dead then
        room:handleAddLoseSkills(to, self.name, nil, true, false)
      end
    end
  end,
}
local dayi = fk.CreateTriggerSkill{
  name = "lingling__dayi",
  anim_type = "offensive",
  events = {fk.TurnEnd, fk.Death},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target:hasSkill(piyun, true, true) then
      if event == fk.TurnEnd then
        return not target.dead and #player.room.logic:getEventsOfScope(GameEvent.UseCard, 4, function(e)
          return e.data[1].from == target.id
        end, Player.HistoryTurn) < 4
      elseif event == fk.Death then
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.TurnEnd then
      local prompt = "#lingling__dayi-invoke::"..target.id
      if target == player then
        prompt = "#lingling__dayi2-invoke"
      end
      if player.room:askForSkillInvoke(player, self.name, nil, prompt) then
        self.cost_data = {tos = {target.id}}
        return true
      end
    elseif event == fk.Death then
      self.cost_data = {tos = {target.id}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
      if target.dead then return end
      target:drawCards(target == player and 3 or 2, self.name)
    elseif event == fk.Death then
      room:changeMaxHp(player, 1)
      if player.dead then return end
      if player:isWounded() then
        room:recover{
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
        if player.dead then return end
      end
      if not target:isNude() then
        room:moveCardTo(target:getCardIds("he"), Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    end
  end,
}
yangguang:addSkill(piyun)
yangguang:addSkill(dayi)
Fk:loadTranslationTable{
  ["lingling__yangguang"] = "杨广",
  ["#lingling__yangguang"] = "灾淹冕旒",
  ["designer:lingling__yangguang"] = "伶",
  ["illustrator:lingling__yangguang"] = "珊瑚虫",

  ["lingling__piyun"] = "辟运",
  [":lingling__piyun"] = "回合开始时，你摸一张牌，然后将一张牌交给任意角色。回合结束时，你可以减1点体力上限，令一名其他角色获得此技能。",
  ["lingling__dayi"] = "大役",
  [":lingling__dayi"] = "有〖辟运〗的角色回合结束时，若其本回合使用牌少于四张，你可以对其造成1点伤害令其摸两张牌（若为你则多摸一张）。"..
  "有〖辟运〗的角色死亡时，你加1点体力上限并回复1点体力，获得其所有牌。"..
  "<br><br> <font color='#a40000'>磬南山之竹，书罪无穷；决东海之波，流恶难尽。",
  ["#lingling__piyun-give"] = "辟运：请将一张牌交给任意角色",
  ["#lingling__piyun-choose"] = "辟运：你可以减1点体力上限，令一名角色获得“辟运”",
  ["#lingling__dayi-invoke"] = "大役：是否对 %dest 造成1点伤害，令其摸两张牌？",
  ["#lingling__dayi2-invoke"] = "大役：是否对你造成1点伤害并摸三张牌？",
}

Fk:loadTranslationTable{
  ["lingling__duguqieluo"] = "孤独伽罗",
  ["#lingling__duguqieluo"] = "一代贤后",
  ["designer:lingling__duguqieluo"] = "伶",
  ["illustrator:lingling__duguqieluo"] = "珊瑚虫",

  ["lingling__tingzheng"] = "听政",
  [":lingling__tingzheng"] = "每轮限一次，其他角色使用锦囊牌指定目标时，你可以使之多指定一个目标或取消一个目标。",
  ["lingling__huanchao"] = "缓朝",
  [":lingling__huanchao"] = "每回合限一次，当一名角色造成伤害时，你可以令伤害-1，则其令你摸两张牌或弃置你一张牌，其本回合下一次造成的伤害+1。"..
  "<br><br> <font color='#a40000'>贵戚之盛，莫与为比。谦卑自守，世以为贤。",
}

local gaojiong = General(extension, "lingling__gaojiong", "sui", 3, 5)
local shuchen = fk.CreateTriggerSkill{
  name = "lingling__shuchen",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick then
      local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn_event and turn_event.data[1] == player then
        local n = #player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
          return e.data[1].from == player.id
        end, Player.HistoryTurn)
        if n == #table.filter(player.player_skills, function (s)
          return s:isPlayerSkill(player) and s.visible
        end) then
          self.cost_data = n
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(self.cost_data, self.name)
  end,

  refresh_events = {fk.AfterCardUseDeclared},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(self, true) and data.card.type == Card.TypeTrick
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
    if turn_event and turn_event.data[1] == player then
      room:addPlayerMark(player, "@lingling__shuchen-turn", 1)
    end
  end,
}
local juxian = fk.CreateTriggerSkill{
  name = "lingling__juxian",
  anim_type = "special",
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_cost = function (self, event, target, player, data)
    local skills = LUtil.GetRandomSkills(player, 5)
    if #skills == 0 then return end
    local result = player.room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseSkillBox.qml", {
        skills, 0, 1, "#lingling__juxian-choice", {},
      })
    if result ~= "" and #json.decode(result) > 0 then
      self.cost_data = {choice = json.decode(result)[1]}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, self.name, self.cost_data.choice)
    room:handleAddLoseSkills(player, self.cost_data.choice, nil, true, false)
  end,
}
local juxian_delay = fk.CreateTriggerSkill{
  name = "#lingling__juxian_delay",
  mute = true,
  priority = 2,
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:getMark("lingling__juxian") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local skill = player:getMark("lingling__juxian")
    room:setPlayerMark(player, "lingling__juxian", 0)
    if not player:hasSkill(skill, true) then return end
    if room:askForSkillInvoke(player, "lingling__juxian", nil, "#lingling__juxian-ask:::"..skill) then
      room:changeMaxHp(player, -1)
    else
      room:handleAddLoseSkills(player, "-"..skill, nil, true, false)
    end
  end,
}
juxian:addRelatedSkill(juxian_delay)
gaojiong:addSkill(shuchen)
gaojiong:addSkill(juxian)
Fk:loadTranslationTable{
  ["lingling__gaojiong"] = "高颎",
  ["#lingling__gaojiong"] = "天降良辅",
  ["designer:lingling__gaojiong"] = "伶",
  ["illustrator:lingling__gaojiong"] = "珊瑚虫",

  ["lingling__shuchen"] = "枢臣",
  [":lingling__shuchen"] = "你回合内，当你本回合第X次使用锦囊牌结算后，你摸X张牌（X为你的技能数）。",
  ["lingling__juxian"] = "举贤",
  [":lingling__juxian"] = "回合开始时，你可以从随机五个技能里选择一个获得，下回合开始时你选择：失去之；减1点体力上限使之永久保留。"..
  "<br><br> <font color='#a40000'>抗节不阿，矫枉无挠。",
  ["@lingling__shuchen-turn"] = "枢臣",
  ["#lingling__juxian-choice"] = "举贤：你可以获得其中一个技能直到下回合开始",
  ["#lingling__juxian-ask"] = "举贤：是否减1点体力上限保留“%arg”？",
}

return extension
